//
//  WmcVMProtocol.swift
//  WmcMVVM-Demo
//
//  Created by 赵新 on 2021/11/25.
//

import UIKit



// MARK: - [WmcVMProtocol]

/// 用于生成ViewModel的协议
protocol WmcVMProtocol: NSObject {
    associatedtype VMType: WmcBaseVM
    /// 设置ViewModel
    func setViewModel(_ vm: VMType)
}

private var k_viewModel = "k_viewModel"
extension WmcVMProtocol {
    /// 该对象的ViewModel
    var viewModel: VMType {
        set { YPRuntime.Set(object: self, key:  &k_viewModel, value:  newValue) }
        get {
            guard let vm: VMType = YPRuntime.GetObject(self, key: &k_viewModel) else {
                let vm = VMType()
                self.viewModel = vm
                return vm
            }
            return vm
        }
    }
    
    /// 设置ViewModel
    func setViewModel(_ vm: VMType) {
        self.viewModel = vm
        if let vc = self as? UIViewController {
            vc.title = vm.title
        }
    }
}

extension WmcVMProtocol where Self: UIViewController {
    /// 由WmcVMProtocol扩展一个实例化方法
    /// - Parameter viewModel: VMType
    init(_ viewModel: VMType) {
        self.init()
        setViewModel(viewModel)
    }
}

extension WmcVMProtocol where Self: UIView {
    /// 由WmcVMProtocol扩展一个实例化方法
    /// - Parameter viewModel: VMType
    init(_ viewModel: VMType) {
        self.init()
        setViewModel(viewModel)
    }
}
